package com.lms.logistics_management_system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lms.logistics_management_system.common.Constants;
import com.lms.logistics_management_system.common.Result;
import com.lms.logistics_management_system.controller.dto.ComboItemDto;
import com.lms.logistics_management_system.controller.dto.DepartmentAndItemDto;
import com.lms.logistics_management_system.controller.dto.DoctorDto;
import com.lms.logistics_management_system.controller.dto.ItemDto;
import com.lms.logistics_management_system.entity.*;
import com.lms.logistics_management_system.exception.ServiceException;
import com.lms.logistics_management_system.mapper.ComboItemMapper;
import com.lms.logistics_management_system.mapper.ComboMapper;
import com.lms.logistics_management_system.mapper.DoctorMapper;
import com.lms.logistics_management_system.mapper.ItemMapper;
import com.lms.logistics_management_system.mapper.dto.ItemListDto;
import com.lms.logistics_management_system.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ComboService extends ServiceImpl<ComboMapper, Combo> {

    @Autowired
    private ComboMapper comboMapper;

    @Autowired
    private ComboItemMapper comboItemMapper;

//            System.out.println("==========" + comboId);
//        System.out.println("==========" + comboPrice);

    public Result addCombo(Integer comboId,double comboPrice,int[] itemIdList) {
        try {
            LambdaQueryWrapper<Combo> lqw = Wrappers.lambdaQuery();
            lqw.eq(Combo::getComboId, comboId);//查找是否已存在
            Combo combo1 = comboMapper.selectOne(lqw);
            if (combo1 == null) { //新增
                //添加combo
                Combo combo = new Combo(comboId,comboPrice);
                comboMapper.insert(combo);
                //添加Comboitem
                ComboItem comboItem = new ComboItem();
                comboItem.setComboId(comboId);
                for (int i = 0; i<itemIdList.length; i++) {
                    Integer itemId = itemIdList[i];
                    comboItem.setItemId(itemId);
                    comboItemMapper.insert(comboItem);
                }
                return Result.success();
            }
            else{
                return Result.error(Constants.CODE_600,"套餐数据已存在");
            }
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_500, "套餐数据新增失败！");
        }
    }


        public List<ComboItemDto> getAllComboItem(){
        List<ComboItemDto> allComboItem;
        try {
            allComboItem = comboMapper.getAllComboItem();
        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"获取套餐信息失败，可能sql错误");
        }
        return allComboItem;
    }

    //获取
    public List<ComboItemDto> getComboItemById(Integer comboId){
        System.out.println("==========" + comboId);
        List<ComboItemDto> allComboItem ;
        try {
            allComboItem = comboMapper.getComboItemById(comboId);
        }catch(Exception e){
            System.out.println(e);
            throw new ServiceException(Constants.CODE_500,"获取套餐信息失败，可能sql错误");
        }
        return allComboItem;
    }


    public Result updateCombo(Integer comboId,double comboPrice,int[] itemIdList) {
        try {
            //更新Combo
            if ( comboPrice>0 ){
                Combo combo = new Combo(comboId,comboPrice);
                comboMapper.updateById(combo);
            }
            if (itemIdList != null){
                //更新ComboItem
                LambdaQueryWrapper<ComboItem> lqw = Wrappers.lambdaQuery();
                lqw.eq(ComboItem::getComboId, comboId);
                List<ComboItem> comboItems = comboItemMapper.selectList(lqw);//匹配所有combo的ite
                Map<ComboItem,Integer> map = new HashMap<>();
                comboItems.forEach(comboItem -> {
                    map.put(comboItem,0);//0标识是否在itemIdList中 变1则有
                });

                for (int i = 0; i<itemIdList.length; i++) {
                    lqw = Wrappers.lambdaQuery();
                    lqw.eq(ComboItem::getComboId, comboId).eq(ComboItem::getItemId, itemIdList[i]);//用于匹配item
                    ComboItem comboItem1 = comboItemMapper.selectOne(lqw);
                    if (comboItem1!=null) {//匹配到已有
                        map.put(comboItem1,1);
                    }else{
                        ComboItem comboItem_new = new ComboItem(comboId, itemIdList[i]);
                        comboItemMapper.insert(comboItem_new);
                    }
                }
                map.forEach((comboItem,has)-> {//若没有遍历到项目,则删除
                    if (has == 0) comboMapper.deleteComboBy2Id(comboItem.getComboId(),comboItem.getItemId());
                });
            }
            return Result.success();
        }catch(Exception e){
            System.out.println(e);
            throw new ServiceException(Constants.CODE_500,"更新套餐信息失败");
        }
    }

//    @Test
//    public void testSelectMap(){
//        //创建Map,封装查询条件
//        Map<String,Object> map = new HashMap<>();
//        //key是字段名， value：字段值 ，多个key，是and 联接
//        map.put("name","zhangsan");
//        map.put("age",20);
//
//        //根据Map查询
//        //SELECT id,name,email,age FROM user WHERE name = ? AND age = ?
//        List<User> users = userDao.selectByMap(map);
//        users.forEach(user -> {
//            System.out.println("selectByMap:"+user);
//        });

    //只获取价格
    private Combo getComboById(Integer comboId){
        QueryWrapper queryWrapper=new QueryWrapper<Combo>();
        queryWrapper.eq("combo_id",comboId);
        try {
            Combo one = getOne(queryWrapper);
            return one;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(Constants.CODE_500,"套餐ID输入错误");
        }
    }

    //根据comboId进行删除
    public boolean removeByComboId(Integer comboId) {
        QueryWrapper queryWrapper=new QueryWrapper<Item>();
        queryWrapper.eq("combo_id",comboId);
        comboItemMapper.delete(queryWrapper);
        return removeById(comboId);
    }

    //批量删除
    public boolean removeByComboIds(List<Integer> comboIds) {
        QueryWrapper queryWrapper=new QueryWrapper<Item>();
        for (int i = 0; i<comboIds.size(); i++) {
            Integer comboId = comboIds.get(i);
            queryWrapper.eq("combo_id", comboId);
            comboItemMapper.delete(queryWrapper);
        }
        return removeByIds(comboIds);

    }
}

    /**
     * 使用Map做多条件查询
     * 方法：selectByMap()
     * 参数：Map<String,Object>
     * 返回值：List<T>
     *
     */


